package study.thread.basic;

/*
 * A线程线程向B线程发送中断请求，可在A线程内调用B.interrupt()
 */
public class InterruptedTest extends Thread {
	static int count = 0;
	
	
	public InterruptedTest(String name) {
		super(name);
	}
	
	public void run() {
		System.out.println(this.getName()+" 开始计算");
		try {
			Thread.sleep(4000);
		} catch (InterruptedException e) {
			System.out.println("主线程被中断，计算终止！");
			e.printStackTrace();
			
			//捕获到中断异常后return，后面的代码不再执行
			return;
		}
		count = (int) (Math.random()*1000);
		
		System.out.println(this.getName()+" 结束计算"+count);
	}

	public static void main(String[] args) {
		System.out.println("==========《主线程执行》==========");
		Thread thread = new InterruptedTest("计算线程");
		
		thread.start();
		
		System.out.println("count=====> "+count);
		try {
			long start = System.currentTimeMillis();
			//主线程暂停2000ms
			thread.join(2000);
			
			//主线程向计算线程发中断请求
			//thread.interrupt();
			
			long end = System.currentTimeMillis();
			
			System.out.println(end-start+" ms 后 count = "+count);
			
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
	}

}
